<template>
  <div class="form-container">
    <back />
    <el-card>
      <template #header>
        <h2 style="text-align: center">预定会议</h2>
      </template>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="会议主题" prop="title">
          <el-input v-model="form.title" placeholder="请输入会议主题"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            class="date-picker"
            v-model="form.startTime"
            type="datetime"
            placeholder="请选择会议开始时间"
            :clearable="false"
            format="YYYY-MM-DD HH:mm:00"
            value-format="YYYY-MM-DD HH:mm:00"
            :disabled-date="disabledBeforeDate"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="请选择会议结束时间"
            :clearable="false"
            format="YYYY-MM-DD HH:mm:00"
            value-format="YYYY-MM-DD HH:mm:00"
            :disabled-date="disabledBeforeDate"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="会议信息" prop="info">
          <el-input
            type="textarea"
            v-model="form.info"
            placeholder="请输入会议信息"
            :autosize="{ minRows: 3, maxRows: 5 }"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { editIntendedMeeting, intendedMeeting, reqMeetingDetail } from '@/api/video';
import { ElMessageBox, type Action, type FormInstance, type FormRules } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';
import back from '@/components/back/index.vue';
import { reqFeedback } from '@/utils/reqFeedback';
import { useRoute, useRouter } from 'vue-router';

interface FormData {
  startTime: string;
  endTime: string;
  title: string;
  info: string;
}

const form = ref<FormData>({
  startTime: '',
  endTime: '',
  title: '',
  info: '',
});

function disabledBeforeDate(date: any) {
  const now = new Date();
  // 禁用今天之前的日期和时间
  return date.getTime() < now.setHours(0, 0, 0, 0);
}

const formRef = ref<FormInstance>();

const router = useRouter();
function submitForm() {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (id.value) {
        // 如果id.value不为空，则是编辑会议
        editIntendedMeeting(form.value).then((res: any) => {
          reqFeedback(res, '修改成功');
        });
      } else {
        // 如果id.value为空，则是新增会议
        intendedMeeting(form.value).then((res: any) => {
          reqFeedback(res, '新增成功');
        });
      }
      router.push({
        name: 'personalCenterMeetingList',
      });
    }
  });
}

// 表单校验
const rules = reactive<FormRules>({
  title: [{ required: true, message: '请输入会议主题', trigger: 'blur' }],
  info: [{ required: true, message: '请输入会议介绍', trigger: 'blur' }],
  startTime: [
    { type: 'date', required: true, message: '请选择会议开始时间', trigger: 'change' },
    { validator: validateStartTime, trigger: 'change' },
  ],
  endTime: [
    { type: 'date', required: true, message: '请选择会议结束时间', trigger: 'change' },
    { validator: validateEndTime, trigger: 'change' },
  ],
});
function validateStartTime(rule: any, value: any, callback: any) {
  const now = Date.now();
  const endTime = new Date(form.value.endTime).getTime();
  const startTime = new Date(form.value.startTime).getTime();
  if (startTime < now) {
    return callback(new Error('开始时间不能小于当前时间'));
  }
  if (!Number.isNaN(endTime) && endTime < startTime) {
    return callback(new Error('开始时间不能大于结束时间'));
  }
  if (!Number.isNaN(endTime)) {
    formRef.value?.validateField('endTime');
  }
  callback();
}
function validateEndTime(rule: any, value: any, callback: any) {
  const now = Date.now();
  const endTime = new Date(form.value.endTime).getTime();
  const startTime = new Date(form.value.startTime).getTime();
  if (endTime < now) {
    return callback(new Error('结束时间不能小于当前时间'));
  }
  if (!Number.isNaN(startTime) && endTime < startTime) {
    return callback(new Error('结束时间不能小于开始时间'));
  }
  if (!Number.isNaN(startTime)) {
    formRef.value?.validateField('startTime');
  }
  callback();
}

function resetForm() {
  ElMessageBox.alert('确定清空预定会议的信息吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    callback: (action: Action) => {
      if (action === 'confirm') {
        formRef.value?.resetFields();
      }
    },
  });
}

// 如果传递了id，则表明是用户编辑会议，则回显表单信息
const route = useRoute();
const id = ref('');
onMounted(() => {
  id.value = route.query.id as string;
  if (id.value) {
    getMeetingDetail();
  }
});
function getMeetingDetail() {
  reqMeetingDetail(id.value).then((res: any) => {
    if (res.code === 200) {
      form.value = {
        ...res.data,
      };
    }
  });
}
</script>

<style lang="scss" scoped>
.form-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}
</style>
